#include "Wire.h"

#define PLLCON1 0x8e //command byte 1
#define PLLCON2 0xa0 //command byte 2

String inString="";
unsigned int freq;

#define AddPllWr 0xc2 //TSA5523 write address
#define AddPllRd 0xc3 //TSA5523 read address


unsigned char SendByte(unsigned char a) 
{
	unsigned char i,j; 
	
	for(i=0;i<8;i++)
	{
		if((a&0x80)==0)
		digitalWrite(A4,LOW);
		else
		digitalWrite(A4,HIGH);
    
    digitalWrite(A5,LOW);
    digitalWrite(A5,HIGH);
    digitalWrite(A5,LOW);
		a=a<<1;
		
	}

	digitalWrite(A4,HIGH);

	digitalWrite(A5,LOW);
	digitalWrite(A5,HIGH);
  digitalWrite(A5,LOW);

	delayMicroseconds(10);

	digitalWrite(A4,LOW);
  digitalWrite(A5,LOW);
 if (j==250)
   return(1);
   else
  	return(0);
}


unsigned char ReadByte(void) 
{
		unsigned char i;
		unsigned char Sin;
		pinMode(A4,OUTPUT);
   	pinMode(A5,OUTPUT);	
	
		digitalWrite(A4,HIGH);
		for(i=0;i<8;i++)
		{ 
			Sin<<=1;
			digitalWrite(A5,LOW);
			digitalWrite(A5,HIGH);
			pinMode(A4,INPUT);

			if (digitalRead(A4)==1)
				Sin|=0x01;
			else
				Sin&=0xfe;

			pinMode(A4,OUTPUT);
		}
		return(Sin);
	 } 
	 

void Start(void)   
{
  digitalWrite(A5,HIGH);
  pinMode(A5,OUTPUT); 
  digitalWrite(A5,HIGH);
  digitalWrite(A4,HIGH);
  pinMode(A4,OUTPUT);
	digitalWrite(A4,HIGH);
  digitalWrite(A4,LOW);
  digitalWrite(A5,LOW); 

}

void Stop(void) 
{
	digitalWrite(A4,LOW);
  digitalWrite(A5,LOW);
	digitalWrite(A5,HIGH);
	digitalWrite(A4,HIGH);
}



void SetChan( unsigned long f) 
{
  unsigned char H_data=(f-6500+38900)*16/1000/256;
  unsigned char L_data=(f-6500+38900)*16/1000%256;
  Start();
  SendByte(AddPllWr);
  SendByte(H_data);
  SendByte(L_data);
  SendByte(PLLCON1);
  SendByte(PLLCON2);
  Stop();
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  SetChan(88000);
  Serial.println("input FM in khz,like FM108000 or FM88000");
 }

void loop() {
  // put your main code here, to run repeatedly:
 delay(300);
 // check if data is available 
 if(Serial.available()){
  //read until a terminator. after this point there should only be numbers
  inString = Serial.readStringUntil('M');
  if(inString.equals("F")){
   //read and set freq   
   freq =Serial.parseInt();
   Serial.println((unsigned long)freq+65536);
   SetChan((unsigned long)freq+65536);
  }
 }
}
